package cc.dawning.utiming.lklocation.location.activity;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiSearch;

import cc.dawning.utiming.lklocation.R;
import cc.dawning.utiming.lklocation.location.utils.LocationSearchDialogUtils;
import cc.dawning.utiming.lklocation.location.utils.OpenOtherMapUtil;

import cc.vv.baselibrary.activity.UtimingBaseActivity;
import cc.vv.baselibrary.location.LocationIntentKey;
import cc.vv.lkbasecomponent.util.LKPermissionConstants;
import cc.vv.lkbasecomponent.util.LKPermissionUtil;

public class LocationNewActivity extends UtimingBaseActivity implements LocationSource, AMap.InfoWindowAdapter, View.OnClickListener {
    /**
     * topBar_返回
     */
    private LinearLayout rl_ln_left_layout;
    /**
     * topBar_title
     */
    private TextView tv_ln_title;
    /**
     * topBar_右侧按钮
     */
    private LinearLayout ll_ln_right_layout;
    /**
     * 地图view
     */
    private MapView mapView;
    /**
     * 我的位置按钮
     */
    private ImageView Iv_location_my;
    /**
     * 导航
     */
    private ImageView Iv_location_he;
    /**
     * 地图搜索
     */
    private GeocodeSearch geocoderSearch;
    /**
     * 刚进入页面定位的经纬度,没有移动MapView
     */
    private LatLng latlng = null;
    /**
     * map对象
     */
    private AMap aMap;
    /**
     * 地图位置变化监听
     */
    private OnLocationChangedListener mListener;
    /**
     * 地图定位监听
     */
    private AMapLocationClient mlocationClient;
    /**
     * 地图定位信息
     */
    private AMapLocationClientOption mLocationOption;
    /**
     * Poi查询条件类
     */
    private PoiSearch.Query query;
    /**
     * //定位监听
     */
    private MyLocationListener mMyLocationListener;
    /**
     * //将经纬度转换为详细地址
     */
    private RegeocodeSearchListener mRegeocodeSearch;
    /**
     * 传递过来的纬度
     */
    private double intent_Latitude;
    /**
     * 传递过来的经度
     */
    private double intent_Longitude;
    /**
     * 传递过来的位置信息
     */
    private String intent_title;
    /**
     * 传递过来的详细位置信息
     */
    private String intent_detail_address;

    /**
     * 传递过来的图片地址
     */
    private String intent_imagePath;
    /**
     * 位置信息实体类
     */
    private LatLonPoint latLonPoint;

    /**
     * 地址标题
     */
    private TextView tv_look_location_titleAdd;

    /**
     * 详细地址
     */
    private TextView tv_look_location_detailAdd;

    private RelativeLayout rl_look_location_detailAdd;

    private ImageView iv_look_location_toJump;

    private String address_[] = new String[1];
    private String width;
    private String height;

    boolean ianan = true;

    /**
     * 开始纬度
     */
    private double startLat;

    /**
     * 开始精度
     */
    private double startLon;

    /**
     * 开始地址
     */
    private String locationAddress = "";

    /**
     * 当前城市
     */
    private String locationCity = "";

    /**
     * 地图打点
     */
    private Marker regeoMarker;
    private Dialog centerDialog;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location_new);
        initView();
        initData();
        initClickListener();

        // 此方法必须重写
        mapView.onCreate(savedInstanceState);
    }

    @Override
    protected void initView(@Nullable Bundle bundle) {
        super.initView(bundle);
    }

    /**
     * 初始化子控件
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView() {
        mapView = findViewById(R.id.mapView);
        Iv_location_my = findViewById(R.id.Iv_location_my);
        Iv_location_he = findViewById(R.id.Iv_location_he);
        rl_ln_left_layout = findViewById(R.id.rl_ln_left_layout);
        tv_ln_title = findViewById(R.id.tv_ln_title);
        ll_ln_right_layout = findViewById(R.id.ll_ln_right_layout);
        tv_look_location_titleAdd = findViewById(R.id.tv_look_location_titleAdd);
        tv_look_location_detailAdd = findViewById(R.id.tv_look_location_detailAdd);
        rl_look_location_detailAdd = findViewById(R.id.rl_look_location_detailAdd);
        iv_look_location_toJump = findViewById(R.id.iv_look_location_toJump);
        boolean locationPermission = LKPermissionUtil.isGranted(LKPermissionConstants.LOCATION);
        if (locationPermission) {
            LKPermissionUtil.permission(LKPermissionConstants.LOCATION).request();
            Toast.makeText(this, "无定位权限，请尝试在手机应用权限管理中打开权限", Toast.LENGTH_SHORT).show();
        }
        init();
        //初始化dialog
        initExitCompanyDialog();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        Bundle bundle = getIntent().getBundleExtra("LOCATION_BUNDLE");
        if (null == bundle) {
            return;
        }
        intent_Latitude = bundle.getDouble(LocationIntentKey.LOCATION_LATITUDE);
        intent_Longitude = bundle.getDouble(LocationIntentKey.LOCATION_LONGITUDE);
        intent_title = bundle.getString(LocationIntentKey.LOCATION_TITLE_TEXT);
        intent_detail_address = bundle.getString(LocationIntentKey.LOCATION_DETAIL_ADDRESS_TEXT);
        width = bundle.getString("width");
        height = bundle.getString("height");
        address_ = intent_title.split("市");
        intent_imagePath = bundle.getString("IMAGEPAHT");
        latLonPoint = new LatLonPoint(intent_Latitude, intent_Longitude);
        tv_look_location_titleAdd.setText(intent_title);
        tv_look_location_detailAdd.setText(intent_detail_address);
        getAddress(latLonPoint);
    }

    /**
     * 设置点击监听
     */
    private void initClickListener() {
        Iv_location_my.setOnClickListener(this);
        Iv_location_he.setOnClickListener(this);
        rl_ln_left_layout.setOnClickListener(this);
        ll_ln_right_layout.setOnClickListener(this);
        rl_look_location_detailAdd.setOnClickListener(this);
        iv_look_location_toJump.setOnClickListener(this);
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }


    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(mMyLocationListener);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 定位实现LocationSource接口的方法结束。
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.Iv_location_my) {
            //我的位置
            if (null != latlng) {
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(latlng));
                aMap.moveCamera(CameraUpdateFactory.zoomTo(17f));
            }
        } else if (id == R.id.Iv_location_he) {
            //导航
            getAddress(latLonPoint);
        } else if (id == R.id.rl_ln_left_layout) {
            finish();
        } else if (id == R.id.ll_ln_right_layout) {
            //右侧菜单
            centerDialog.show();
        } else if (id == R.id.rl_look_location_detailAdd) {
            //打开地图
//            Intent intent = new Intent("android.intent.action.VIEW",
//                    android.net.Uri.parse("androidamap://showTraffic?sourceApplication=softname&amp;poiid=BGVIS1&amp;lat=36.2&amp;lon=116.1&amp;level=10&amp;dev=0"));
//            intent.setPackage("com.autonavi.minimap");
//            startActivity(intent);


        } else if (id == R.id.iv_look_location_toJump) {
            showDialog();
        } else {

            return;
        }

    }


    /**
     * 初始化AMap对象
     */
    private void init() {
        if (mMyLocationListener == null) {
            mMyLocationListener = new MyLocationListener();
        }
        if (mRegeocodeSearch == null) {
            mRegeocodeSearch = new RegeocodeSearchListener();
        }
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
            regeoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
                    .icon(BitmapDescriptorFactory
                            .fromResource(R.mipmap.icon_local)).draggable(true));
        }
    }


    // 定位监听
    private class MyLocationListener implements AMapLocationListener {

        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (mListener != null && amapLocation != null) {
                if (amapLocation != null && amapLocation.getErrorCode() == 0) {
                    // 显示系统小蓝点

                    mListener.onLocationChanged(amapLocation);
                    //获取纬度
                    double Latitude = amapLocation.getLatitude();

                    startLat = Latitude;

                    //获取经度
                    double Longitude = amapLocation.getLongitude();

                    startLon = Longitude;

                    locationAddress = amapLocation.getAddress();
                    locationCity = amapLocation.getCity();
                    latlng = new LatLng(Latitude, Longitude);
                    if (ianan) {
                        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(convertToLatLng(latLonPoint), 17));
                        aMap.moveCamera(CameraUpdateFactory.changeLatLng(convertToLatLng(latLonPoint)));
                        regeoMarker.setPosition(convertToLatLng(latLonPoint));
//                        if (address_.length == 2) {
//                            regeoMarker.setTitle(address_[1]);
//                        } else {
//                            regeoMarker.setTitle(intent_title);
//                        }
                        regeoMarker.showInfoWindow();
                    }
                    ianan = false;
                } else {
                    //定位失败
                }
            }
        }
    }

    /**
     * 将经纬度转换成具体地址信息。
     */
    private class RegeocodeSearchListener implements GeocodeSearch.OnGeocodeSearchListener {
        @Override
        public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
            if (rCode == 1000) {
                if (result != null && result.getRegeocodeAddress() != null
                        && result.getRegeocodeAddress().getFormatAddress() != null) {
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(convertToLatLng(latLonPoint)));
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(17f));
//                    regeoMarker.setPosition(convertToLatLng(latLonPoint));
                }
            }
        }

        @Override
        public void onGeocodeSearched(GeocodeResult result, int rCode) {

        }
    }


    public LatLng convertToLatLng(LatLonPoint latLonPoint) {
        return new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude());
    }

    /**
     * 自定义系统定位小蓝点
     */
    private void setUpMap() {
        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        // 设置小蓝点的图标
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_look_location_mypos));
        // 设置圆形的边框颜色
        myLocationStyle.strokeColor(Color.TRANSPARENT);
        // 设置圆形的填充颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        //设置小蓝点的锚点
        // myLocationStyle.anchor(int,int)
        // 设置圆形的边框粗细
        myLocationStyle.strokeWidth(0.1f);
        aMap.setMyLocationStyle(myLocationStyle);
//        aMap.setMyLocationRotateAngle(180);
        // 设置定位监听
        aMap.setLocationSource(this);
        // 设置默认定位按钮是否显示
        aMap.getUiSettings().setMyLocationButtonEnabled(false);
        // 设置缩放按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);
        // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setMyLocationEnabled(true);
        aMap.setInfoWindowAdapter(new MyInforw());
        aMap.moveCamera(CameraUpdateFactory.zoomTo(17f));
        geocoderSearch = new GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(mRegeocodeSearch);

        LatLng latlng = new LatLng(intent_Latitude, intent_Longitude);
        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng, 17));
    }

    /**
     * 位置打点显示  显示位置信息
     */
    private class MyInforw implements AMap.InfoWindowAdapter {

        @Override
        public View getInfoWindow(Marker marker) {
            return null;
        }

        @Override
        public View getInfoContents(Marker marker) {
            View infor = getLayoutInflater().inflate(R.layout.activity_location_marker, null);
            LinearLayout Lin_marker = infor.findViewById(R.id.Lin_marker);
            Lin_marker.getBackground().setAlpha(200);
            TextView title = infor.findViewById(R.id.Tv_title);
            if (address_.length == 2) {
                title.setText(address_[1]);
            } else {
                title.setText(intent_title);
            }
            return infor;
        }
    }

    /**
     * 响应逆地理编码
     */
    public void getAddress(final LatLonPoint latLonPoint) {
        // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);
        // 设置同步逆地理编码请求
        geocoderSearch.getFromLocationAsyn(query);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        getAddress(latLonPoint);
    }

    /**
     * 转发的弹窗
     */
    private void initExitCompanyDialog() {
        final View layoutView = LayoutInflater.from(this).inflate(R.layout.window_exit_company, null);

        centerDialog = LocationSearchDialogUtils.getCenterDialog(this, layoutView, 0, 0);
        final TextView tv_picture = (TextView) layoutView.findViewById(R.id.tv_picture);
        tv_picture.setText("分享位置");
        tv_picture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                centerDialog.dismiss();
                String messageContent = intent_Latitude + "," + intent_Longitude + "," + intent_title + "," + intent_imagePath + "," + width + "," + height;
                // TODO: 2018/3/23 转发

            }
        });
    }


    /**
     * 打开定位应用
     */
    private void showDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_open_map, null);
        final Dialog dialog = LocationSearchDialogUtils.getBottomDialog(this, view);
        dialog.show();
        LinearLayout ll_location_gaoDeMap = view.findViewById(R.id.ll_location_gaoDeMap);
        LinearLayout ll_location_baiDuMap = view.findViewById(R.id.ll_location_baiDuMap);
        LinearLayout ll_location_tencentMap = view.findViewById(R.id.ll_location_tencentMap);
        LinearLayout ll_location_cancel = view.findViewById(R.id.ll_location_cancel);
        ll_location_gaoDeMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                OpenOtherMapUtil.getInstance().openGaoDeMap(LocationNewActivity.this,
                        locationAddress, intent_detail_address, intent_Latitude + "",
                        intent_Longitude + "");
            }
        });

        ll_location_baiDuMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                OpenOtherMapUtil.getInstance().openBaiDuMap(LocationNewActivity.this, startLat, startLon,
                        locationAddress, intent_Latitude, intent_Longitude, intent_detail_address, locationCity);
            }
        });

        ll_location_tencentMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                OpenOtherMapUtil.getInstance().openTencentMap(LocationNewActivity.this,
                        locationAddress, intent_detail_address, intent_Latitude + "",
                        intent_Longitude + "");
            }
        });
        ll_location_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }


}
